package com.example.util;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-02 14:18
 **/
public class ResponseServletUtil extends HttpServlet {

    protected void response(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置了返回的响应的字符编码
        resp.setContentType("text/html;charset=utf-8");

        //设置缓存头
        resp.setDateHeader("Expires", System.currentTimeMillis() + 10000);
        //不设置缓存
        resp.setDateHeader("Expires", 0);
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Pragma", "no-cache");

        //Refresh后面接上的单位是秒,刷新到其他地址,后面需要拼接上地址,实现定时刷新的功能
        resp.setHeader("Refresh", "10; URL=/index.html");

        //重定向地址就是这个,第一次http请求响应码为302,第二次到真正的响应码上
        resp.sendRedirect("/index.html");

        //重定向地址就是这个,302,307
        resp.setHeader("Location", "/index.html");
        resp.setStatus(302);

        //下载文件
        download(req, resp);

        //注意事项
        //字节流和字符流不用关闭可以,应用会自动帮忙关闭
        //字符流和字节流只能选择一个
        resp.setContentType("text/html;charset=utf-8");
        resp.getOutputStream().write("这是一个寂寞的天,下着有些伤心的雨".getBytes("utf-8"));
        resp.getWriter().write("看来是要出错了");
    }

    protected void download(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ServletContext context = getServletContext();
        //获取文件路径
        String filename = req.getParameter("filename");
        String path = context.getRealPath("/download/" + filename);
        System.out.println("真是路径: " + path);
        //获取文件
        File file = new File(path);
        //注意: 需要先设置头,再读取流,不然文件可能会在浏览器打开,设置头失效
        //响应中写入流文件类型,MimeType
        // String mimeType = context.getMimeType(filename);
        // resp.setContentType(mimeType);
        //3.设置响应消息头
        //注意下载的时候，设置响应正文的MIME类型，用application / octet - stream
        //application/octet-stream 是应用类型为字节流
        resp.setHeader("Content-Type", "application/octet-stream");
//mime-type结合情况,比如xlsx为
//         resp.setHeader("Content-Type",
//                 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");

        //    文件名写入
        //设置文件名,记得要用ISO-8859-1,不然中文乱码
        resp.setHeader("Content-Disposition", "attachment;filename="
                + new String(filename.getBytes(), "ISO-8859-1"));

        //注意,流需要放到最后写入,不能再设置content-type之前,不然会乱码
        if (file.exists()) {

            //生成输入流
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                 ServletOutputStream os = resp.getOutputStream();) {

                byte[] bytes = new byte[1024];
                int len;

                //生成输入流

                while ((len = bis.read(bytes)) != -1) {
                    os.write(bytes, 0, len);
                }
                //关闭输入流 try 关闭了

            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }

        }

    }

}
